function handleTree(data, id, parentId, children) {
  let config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

let arr = [
  {
    id: 1,
    name: 1,
    parentId: 0,
  },
  {
    id: 2,
    name: 2,
    parentId: 1,
  },

  {
    id: 3,
    name: 3,
    parentId: 0,
  },

  {
    id: 4,
    name: 4,
    parentId: 3,
  },

  {
    id: 5,
    name: 5,
    parentId: 3,
  },

  {
    id: 6,
    name: 6,
    parentId: 0,
  },
];

let b = handleTree(arr);
console.log("b : ", JSON.stringify(b));
